package com.ptkc.utils;

import com.ptkc.core.esearch.model.Order;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;

/**
 * @author: Mr.Jiao
 * @date: 2018年12月20日
 */
public abstract class SingleThreadRunner<V> extends Thread implements Runnable{

    private final ConcurrentHashMap<String, V> concurrentHashMap = new ConcurrentHashMap();

    @Override
    public final void run() {
        while (true){
            if(concurrentHashMap.keys().hasMoreElements()){
                String k = concurrentHashMap.keys().nextElement();
                V v = concurrentHashMap.remove(k);
                this.run(k, v);
            }else{
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public abstract void run(String key, V v);

    public final void put(String key, V value){
        if (!concurrentHashMap.containsKey(key)) {
            concurrentHashMap.put(key, value);
        }
    }

    @Override
    public final synchronized void start() {
        if (this.getState() == State.NEW){
            super.start();
        }else{
            throw new RuntimeException("线程已经在运行");
        }
    }
}
